import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
import 'dotenv/config';
import helmet from 'helmet';
import { json, urlencoded } from 'body-parser';

import { AppModule } from './app.module';
import { HttpExceptionFilter } from './filters/http-exception.filter';
// import { TransformInterceptor } from './interceptors/transform/transform.interceptor';
// NestJS
const PORT = process.env.PORT || 8080;
// const PREFIX = process.env.PREFIX || '/';
const PREFIX = '/api';
export const IS_DEV = process.env.NODE_ENV !== 'production';
console.log(process.env);
async function bootstrap() {
  const logger: Logger = new Logger('main.ts');
  console.log(IS_DEV, '是否为开发环境');
  const app = await NestFactory.create(AppModule, {
    // 开启日志级别打印
    logger: IS_DEV ? ['log', 'debug', 'error', 'warn'] : ['error', 'warn'],
  });
  //允许跨域请求
  app.enableCors();
  // 给请求添加prefix
  app.setGlobalPrefix('api');

  // 配置api文档信息(不是生产环境配置文档)
  if (IS_DEV) {
    const options = new DocumentBuilder()
      .setTitle('api文档')
      .setBasePath(PREFIX)
      .addBearerAuth({ type: 'apiKey', in: 'header', name: 'token' })
      .setVersion('0.0.1')
      .build();

    const document = SwaggerModule.createDocument(app, options);
    SwaggerModule.setup(`${PREFIX}/docs`, app, document);
    // 浏览器直接访问 http://localhost:5000/api-json
    SwaggerModule.setup('api', app, document);
  }
  // Web漏洞的
  app.use(helmet());

  app.use(json({ limit: '50mb' }));
  app.use(urlencoded({ limit: '50mb', extended: true }));

  // 全局注册错误的过滤器(错误异常)
  app.useGlobalFilters(new HttpExceptionFilter());
  // 全局注册拦截器(成功返回格式)
  // app.useGlobalInterceptors(new TransformInterceptor());
  await app.listen(PORT, () => {
    logger.debug(process.env);
    logger.log(`服务已经启动,接口请访问:http://wwww.localhost:${PORT}${PREFIX}`);
    logger.log(`服务已经启动,文档请访问:http://wwww.localhost:${PORT}${PREFIX}/docs`);
  });
}
bootstrap();
